package com.xuecheng.manage_cms.service;

import com.xuecheng.framework.domain.cms.CmsTemplate;
import com.xuecheng.framework.domain.cms.response.CmsCode;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.manage_cms.dao.CmsTemplateRepository;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Optional;

@Service
public class TemplateService  {

    @Autowired
    private CmsTemplateRepository cmsTemplateRepository;

    @Autowired
    private GridFsTemplate gridFsTemplate;

    public QueryResponseResult findList(){
        List<CmsTemplate> all = cmsTemplateRepository.findAll();
        QueryResult queryResult = new QueryResult();
        queryResult.setTotal(all.size());
        queryResult.setList(all);
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
    }

    public ResponseResult add(String path,CmsTemplate cmsTemplate) {
        File file = new File(path);
        FileInputStream fileInputStream=null;
        if(file.isFile()&&"ftl".equals(path.substring(path.lastIndexOf(".")+1))){
            try {
                fileInputStream=new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }else {
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        //文件存储后返回一个id
        ObjectId objectId = gridFsTemplate.store(fileInputStream, cmsTemplate.getTemplateName(), "");
        //文件id返回给模板对象
        cmsTemplate.setTemplateFileId(objectId.toString());
        //保存
        cmsTemplateRepository.save(cmsTemplate);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    public ResponseResult del(String templateId){
        Optional<CmsTemplate> byId = cmsTemplateRepository.findById(templateId);
        if (!byId.isPresent()){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }else {
            CmsTemplate cmsTemplate = byId.get();
            String templateFileId = cmsTemplate.getTemplateFileId();
            if (templateFileId==null){
                ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_TEMPLATEISNULL);
            }
            gridFsTemplate.delete(Query.query(Criteria.where("_id").is(templateFileId)));

            cmsTemplateRepository.deleteById(templateId);
        }
        return new ResponseResult(CommonCode.SUCCESS);
    }
}
